import sys
from optparse import OptionParser
from getpass import getpass

from client import BlogClient


def get_options():
    parser = OptionParser()
    parser.usage = """%prog [options] <action>
    actions:
        post - reads a post from stdin and posts it
    """
    parser.add_option(
        '-u', '--username', help='Username (email address)',
        action='store', dest='username', type='string',
    )
    parser.add_option(
        '-p', '--password', help='Password',
        action='store', dest='password', type='string',
    )
    parser.add_option(
        '-n', '--blog-name', help='Your blogger.com blog name',
        action='store', dest='blogname', type='string'
    )
    parser.add_option(
        '-t', '--title', help='Blog Entry Title',
        action='store', dest='title', type='string'
    )
    return parser


class Commander(object):

    def __init__(self):
        self._parser = get_options()
        self._opts, self._args = self._parser.parse_args()
        if not self._args:
            self._parser.error('Must provide an action')
        else:
            self._action = self._args[0]
        callable_action = self._get_action()
        if callable_action is None:
            self._parser.error('Unknown action, Available: "post"')
        else:
            callable_action()

    def _get_action(self):
        return getattr(self, self._action, None)

    def post(self):
        content = sys.stdin.read()
        blogname = self._opts.blogname
        username = self._opts.username
        password = self._opts.password
        title = self._opts.title
        client = BlogClient(blogname, username, password)
        client.post(title, content)

def main():
    Commander()

if __name__ == '__main__':
    main()

